package com.fly.handler;

import com.fly.domain.User;
import com.fly.service.UserService;
import com.fly.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @author Fly
 * @Description
 * @Date Created in 8:25 2018/1/25
 * @Modified by
 */
@Component
public class UserHandler {

    private final UserService userService;

    @Autowired
    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    /**
     * 保存
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> save(ServerRequest serverRequest){
        Mono<User> userMono = serverRequest.bodyToMono(User.class);
        userService.save(userMono.block());
        Response response = new Response(true,"保存成功",null);
        return ServerResponse.ok().body(fromObject(response));
    }

    /**
     * 查询列表
     * @param serverRequest
     * @return
     */
  //  @PreAuthorize("hasPermission(#serverRequest, 'admin')")
    public Mono<ServerResponse> list(ServerRequest serverRequest){
        Flux<User> userFlux = Flux.fromIterable(userService.findAll());
        return ServerResponse.ok().body(userFlux,User.class);
    }

    /**
     * 删除用户
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> delete(ServerRequest serverRequest){
        String ids = serverRequest.pathVariable("ids");
        userService.removeUsers(ids);
        Response response = new Response(true,"删除成功",null);
        return ServerResponse.ok().body(fromObject(response));
    }
}
